# -*- coding: utf-8 -*-
# @Time    : 2020/9/14 12:25
# @Author  : liuwenfan
# @File    : group_service.py
# @Software: PyCharm
import json
import time

import requests

from application import db
from application.libs import const
from application.models.models import Case, Node, Taskcase


def call_method(case_id, sign, node_id, task_id, **extend):
    """
    远程控制生成目录以及git代码-停止/启动/部署
    :param case_id:
    :param sign:
    :param extend:
    :return: messsge
    """
    case = db.session.query(Case).filter(Case.id == case_id).one()
    headers = {'Content-Type': 'application/json'}
    # 通过节点管理，不需要在这指定节点机器
    # ipv4 = None
    # if case.case_type == 1:
    #     ipv4 = Config.WEB_NODE
    # elif case.case_type == 2:
    #     ipv4 = Config.APP_NODE
    data = {
        "groupDir": case.group_name,
        "projectDir": case.project_name,
        "caseName": case.case_name,
        "gitPath": case.case_value

    }
    value = {}
    value.update(extend)
    value.update(data)
    value.update({"case_id": case_id})
    # 改掉拼接得参数,注意ipv4得数据格式~！！！！！！,返回值再修改一下
    # url = "http://{}:9527/{}".format(ipv4, sign)
    n = db.session.query(Node).filter(Node.id == node_id).one()
    url = "http://{}:{}/{}".format(n.ipv4, n.ipv4_port, sign)

    try:
        text = requests.get(url=url, headers=headers, data=json.dumps(value))
        if text.text == "success":
            if sign == "deployee":
                # db.session.query(Case).filter(Case.id == case_id).update({"is_deploy": 1})
                db.session.query(Taskcase).filter(Taskcase.task_id == task_id, Taskcase.case_id == case_id, Taskcase.node_id == node_id).update({"is_deploy": 1})
                db.session.commit()
                # case_flag = db.session.query(Case).filter(Case.id == case_id).one()
                # ret = {"msg": case_flag.is_deploy, "code": const.SUCCESS}
                messsge = const.OPERATE_SUCCESS
            else:
                messsge = const.OPERATE_SUCCESS
        else:
            messsge = const.OPERATE_FAIL
    except Exception as e:
        messsge = const.OPERATE_FAIL
    return messsge


def add_case(case_name, group_name, project_name, case_type, case_value):
    """
    用例仓库-新增
    :param case_name: 用例名称
    :param group_name: 业务线
    :param project_name: 项目名称
    :param case_type: 用例类型
    :param case_value: 用例地址
    :return: string
    """
    add_case = Case()
    add_case.case_name = case_name
    add_case.group_name = group_name
    add_case.project_name = project_name
    add_case.case_type = case_type
    add_case.case_value = case_value
    if case_type == 3:
        add_case.is_deploy = 1
    try:
        db.session.add(add_case)
        db.session.commit()
        message = const.INSERT_SUCCESS
    except:
        db.session.rollback()
        message = const.INSERT_FAIL
    return message


def update_case(data):
    """
    用例仓库-修改
    :param data: 主键自增id/用例名称/业务线/项目名称/用例类型/用例地址/是否部署
    :return: string
    """
    id = data["id"]
    case_name = data["case_name"]
    group_name = data["group_name"]
    project_name = data["project_name"]
    case_value = data["case_value"]
    case_type = data["case_type"]
    is_deploy = data["is_deploy"]
    u_time = time.strftime(
        "%Y-%m-%d %H:%M:%S",
        time.localtime())
    db.session.query(Case).filter(Case.id == id).update({"case_name": case_name,
                                                         "group_name": group_name,
                                                         "project_name": project_name,
                                                         "case_type": case_type,
                                                         "case_value": case_value,
                                                         "update_time": u_time,
                                                         "is_deploy": is_deploy})
    try:
        db.session.commit()
        return const.EDIT_SUCCESS
    except:
        # 事務回滾
        db.session.rollback()
        return const.EDIT_FAIL


def get_case_list(case_querys):
    # 拼接查询条件
    parm = []
    if case_querys['is_deploy'] != '':
        parm.append(Case.is_deploy == case_querys['is_deploy'])
    if case_querys['project_name'].strip() != '':
        parm.append(Case.project_name == case_querys['project_name'])
    if case_querys['case_type'] != '':
        parm.append(Case.case_type == case_querys['case_type'])
    if case_querys['case_name'].strip() != '':
        parm.append(Case.case_name.contains(case_querys['case_name']))
    page_data = db.session.query(Case).filter(*parm).order_by(Case.create_time.desc()).paginate(page=case_querys[const.PAGE_NUM],
                                                              per_page=case_querys[const.PAGE_PER], error_out=False)
    response_case_dic = {}
    response_case_list = []
    if page_data.items:
        for msg in page_data.items:
            response_case_dic['id'] = msg.id
            response_case_dic['group_name'] = msg.group_name
            response_case_dic['project_name'] = msg.project_name
            response_case_dic['case_name'] = msg.case_name
            response_case_dic['case_type'] = msg.case_type
            response_case_dic['case_value'] = msg.case_value
            response_case_dic['submit_uid'] = msg.submit_uid
            response_case_dic['update_uid'] = msg.update_uid
            response_case_dic['is_deploy'] = msg.is_deploy
            response_case_dic['create_time'] = msg.create_time.strftime("%Y-%m-%d %H:%M:%S")
            response_case_dic['update_time'] = msg.update_time.strftime("%Y-%m-%d %H:%M:%S")
            response_case_list.append(response_case_dic.copy())
            response_case_dic.clear()
    response_case_dic['items'] = response_case_list
    response_case_dic['total'] = page_data.total
    return response_case_dic

